package com.meshi.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public abstract class CommonDAO {
	private static SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			ex.printStackTrace();
			System.out.println("Initial SessionFactory creation failed. " + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactroy() {
		return sessionFactory;
	}
	
	public void add(Object o) {
		Session session = beginTransaction();
		session.save(o);
		commitTransaction(session);
	}
	
	public void delete(int id) {
		Session session = beginTransaction();
		session.delete(session.load(getObjectClass(), id));
		commitTransaction(session);
	}
	
	public void update(Object o) {
		Session session = beginTransaction();
		session.update(o);
		commitTransaction(session);
	}
	
	public Object findById(int id) {
		Session session = beginTransaction();
		Object result = session.get(getObjectClass(), id);
		commitTransaction(session);
		return result;
	}
	
    protected abstract Class getObjectClass();
	
	private Session beginTransaction() {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		return session;
	}
	
	private void commitTransaction(Session session) {
		session.getTransaction().commit();
	}
}
